package com.ssm.pre.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ssm.pre.bean.AccessToken;
import com.ssm.pre.bean.Button;
import com.ssm.pre.bean.CommonButton;
import com.ssm.pre.bean.ComplexButton;
import com.ssm.pre.bean.Menu;
import com.ssm.pre.bean.ViewButton;
import com.ssm.pre.dao.WechatAppDao;
import com.ssm.pre.dao.WechatMenuDao;
import com.ssm.pre.service.WechatMenuService;
import com.ssm.pre.util.DateUtil;
import com.ssm.pre.util.PageCount;
import com.ssm.pre.util.ToolUtil;
import com.ssm.pre.util.WeixinUtil;
import com.ssm.util.Constants;
import com.ssm.util.object.InputObject;
import com.ssm.util.object.OutputObject;

@Service
public class WechatMenuServiceImpl implements WechatMenuService {

	@Autowired
	private WechatMenuDao wechatMenuDao;
	
	@Autowired
	private WechatAppDao wechatAppDao;
	/**
	 * 生成菜单版本号
	 */
	@Override
	public void getmenuVersion(InputObject inputObject, OutputObject outputObject) throws Exception {
		Map<String, Object> map = inputObject.getParams();
		map.put("menuVersion", DateUtil.getToString());
		outputObject.setBean(map);
	}

	/**
	 * 查找相同的菜单版本号
	 * @throws Exception 
	 */
	@Override
	public void selectMenuByVersion(InputObject inputObject, OutputObject outputObject) throws Exception {
		Map<String, Object> map = inputObject.getParams();
		List<Map<String, Object>> beans = wechatMenuDao.selectMenuByVersion(map);
		
		for(Map<String, Object> bean : beans){
			//查询一级菜单的子菜单
			List<Map<String,Object>> beanItems = wechatMenuDao.selectMenuByBelong(bean);
			bean.put("beanItems", beanItems);
		}
		outputObject.setBeans(beans);
		
	}

	/**
	 * 查询所有的微信自定义菜单
	 */
	@Override
	public void queryMenuByList(InputObject inputObject, OutputObject outputObject) throws Exception {
		Map<String, Object> map = inputObject.getParams();
		List<Map<String, Object>> beans = wechatMenuDao.queryMenuByList(map);
		int page = Integer.parseInt(map.get("offset").toString())/Integer.parseInt(map.get("limit").toString());
		page++;
		List<Map<String, Object>> params = PageCount.page(beans, page, Integer.parseInt(map.get("limit").toString()));
		outputObject.setBeans(params);
		outputObject.settotal(beans.size());
	}

	/**
	 * 添加微信自定义菜单 一级菜单
	 */
	@Override
	public void addMenuByOne(InputObject inputObject, OutputObject outputObject) throws Exception {
		Map<String, Object> map = inputObject.getParams();
		
		map.put("menuType","click");
		map.put("menuKey", DateUtil.getToString());
		map.put("menuBelong", 0);
		map.put("hasChild", 0);
//        params.put("publishTime",  "-");
		map.put("createId", inputObject.getLogParams().get("id"));
		map.put("createTime", DateUtil.getTimeAndToString());
		map.put("wetherPublish", 0);
		map.put("wetherUser", 0);
        wechatMenuDao.addMenuByOne(map);
	}

	/**
	 * 根据ID修改一条记录
	 */
	@Override
	public void updateMenuById(InputObject inputObject, OutputObject outputObject) throws Exception {
		Map<String, Object> map = inputObject.getParams();
		if(!ToolUtil.contains(map,Constants.BUTTOMMENU_KEY,Constants.BUTTOMMENU_RETURNMESSAGE, inputObject, outputObject)){
			return ;
		}
		if(map.get("rebackInt").equals("6"))
			map.put("menuType", "view");
		else
			map.put("menuType", "click");
		wechatMenuDao.updateMenuById(map);
	}

	/**
	 * 根据ID查询一条记录
	 */
	@Override
	public void selectMenuById(InputObject inputObject, OutputObject outputObject) throws Exception {
		Map<String, Object> map = inputObject.getParams();
		Map<String, Object> bean = wechatMenuDao.selectMenuById(map);
		outputObject.setBean(bean);
	}

	/**
	 * 添加微信自定义菜单 二级菜单
	 */
	@Override
	public void addMenuByTwo(InputObject inputObject, OutputObject outputObject) throws Exception {
		Map<String, Object> map = inputObject.getParams();
		map.put("menuType","click");
		map.put("menuKey", DateUtil.getToString());
		
		map.put("hasChild", 0);
//        params.put("publishTime",  "-");
		map.put("createId", inputObject.getLogParams().get("id"));
		map.put("createTime", DateUtil.getTimeAndToString());
		map.put("wetherPublish", 0);
		map.put("wetherUser", 0);
		
		//根据menuBelong修改一级菜单的hasChild
		Map<String,Object> params=new HashMap<String, Object>();
		params.put("id", map.get("menuBelong"));
		params.put("hasChild", 1);
		wechatMenuDao.updateMenuHasChildById(params);
		
        wechatMenuDao.addMenuByOne(map);
	}

	/**
	 * 发布菜单 更新菜单发布状态和发布人信息
	 */
	@Override
	public void updateMenuPublish(InputObject inputObject, OutputObject outputObject) throws Exception {
		Map<String, Object> map = inputObject.getParams();
		List<Map<String, Object>> appBeans = wechatAppDao.queryWechatAppByInit();
		if (appBeans.isEmpty()) {
			outputObject.setreturnMessage("请确认APPID或者APPSECRET存在...");
		} else {
			AccessToken at = WeixinUtil.getAccessToken(appBeans.get(0).get("appId").toString(), appBeans.get(0).get("appSecret").toString());
			if (null != at) {
				// 调用接口创建菜单
				Map<String, Object> bean = new HashMap<>();
				bean.put("menuVersion", map.get("menuVersion"));
				Map<String,Object> result = WeixinUtil.createMenu(selectPublish(bean),at.getToken());
				// 判断菜单创建结果
				if (!result.isEmpty()) {
					if(result.get("returnCode").toString().equals(Constants.WECHAT_BUTTON_MENU_SUCCESS)){
						//修改Publish发布状态
						wechatMenuDao.updateWetherPublish();
						map.put("publishUser",inputObject.getLogParams().get("id"));
						map.put("publishTime", DateUtil.getTimeAndToString());
						wechatMenuDao.updateMenuPublish(map);
						
					}else{
						outputObject.setreturnMessage("创建菜单失败。错误编码errcode：" + result.get("returnCode") + "错误信息errmsg:" + result.get("returnMsg"));
					}
				} else {
					outputObject.setreturnMessage("请求微信服务器失败...");
				}
			}
		}
		
	}
	
	/**
	 * 查询所有的发布菜单
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public Menu selectPublish(Map<String,Object> map) throws Exception{
		// 查询所有的一级菜单
		map.put("menuGrade", "1");
		List<Map<String,Object>> firstBeans = wechatMenuDao.queryAllByGrade(map);
		// 查询所有的二级菜单
		map.put("menuGrade", "2");
		List<Map<String,Object>> secondBeans = wechatMenuDao.queryAllByGrade(map);
		Menu menu = new Menu();
		// 用来存储一级菜单
		List<ComplexButton> btn_0 = new ArrayList<ComplexButton>();
		List<ViewButton> btn_1 = new ArrayList<ViewButton>();
		List<CommonButton> btn_2 = new ArrayList<CommonButton>();
		for (Map<String,Object> bean : firstBeans) {
			ComplexButton mainBtn = new ComplexButton();
			if (Integer.parseInt(bean.get("hasChild").toString()) == 1) {
				// 一级菜单下面有二级菜单
				mainBtn.setName(bean.get("menuName").toString());
				// 用来存储二级菜单
				List<CommonButton> btn1 = new ArrayList<CommonButton>();
				List<ViewButton> btn2 = new ArrayList<ViewButton>();
				for (Map<String,Object> bean1 : secondBeans) {
					if (bean1.get("menuBelong").equals(bean.get("id")) && bean1.get("menuType").equals("click")) {
						// 回复内容的菜单
						CommonButton btnbe = new CommonButton();
						btnbe.setName(bean1.get("menuName").toString());
						btnbe.setType(bean1.get("menuType").toString());
						btnbe.setKey(bean1.get("menuKey").toString());
						btn1.add(btnbe);
					} else if (bean1.get("menuBelong").equals(bean.get("id")) && bean1.get("menuType").equals("view")) {
						// 跳转网页的菜单
						ViewButton btnbe = new ViewButton();
						btnbe.setName(bean1.get("menuName").toString());
						btnbe.setType(bean1.get("menuType").toString());
						btnbe.setUrl(bean1.get("rebackContext").toString());
						btn2.add(btnbe);
					}
				}
				switch (btn1.size() + btn2.size()) {
				case 1:
					switch (btn1.size()) {
					case 0:mainBtn.setSub_button(new Button[] { btn2.get(0) });break;
					case 1:mainBtn.setSub_button(new Button[] { btn1.get(0) });break;
					default:break;
					}break;
				case 2:
					switch (btn1.size()) {
					case 0:mainBtn.setSub_button(new Button[] { btn2.get(0),btn2.get(1) });break;
					case 1:mainBtn.setSub_button(new Button[] { btn1.get(0),btn2.get(0) });break;
					case 2:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1) });break;
					default:break;
					}break;
				case 3:
					switch (btn1.size()) {
					case 0:mainBtn.setSub_button(new Button[] { btn2.get(0),btn2.get(1), btn2.get(2) });break;
					case 1:mainBtn.setSub_button(new Button[] { btn1.get(0),btn2.get(0), btn2.get(1) });break;
					case 2:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn2.get(0) });break;
					case 3:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn1.get(2) });break;
					default:break;
					}
					break;
				case 4:
					switch (btn1.size()) {
					case 0:mainBtn.setSub_button(new Button[] { btn2.get(0),btn2.get(1), btn2.get(2), btn2.get(3) });break;
					case 1:mainBtn.setSub_button(new Button[] { btn1.get(0),btn2.get(0), btn2.get(1), btn2.get(2) });break;
					case 2:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn2.get(0), btn2.get(1) });break;
					case 3:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn1.get(2), btn2.get(0) });break;
					case 4:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn1.get(2), btn1.get(3) });break;
					default:break;
					}break;
				case 5:
					switch (btn1.size()) {
					case 0:mainBtn.setSub_button(new Button[] { btn2.get(0),btn2.get(1), btn2.get(2), btn2.get(3),btn2.get(4) });break;
					case 1:mainBtn.setSub_button(new Button[] { btn1.get(0),btn2.get(0), btn2.get(1), btn2.get(2),btn2.get(3) });break;
					case 2:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn2.get(0), btn2.get(1),btn2.get(2) });break;
					case 3:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn1.get(2), btn2.get(0),btn2.get(1) });break;
					case 4:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn1.get(2), btn1.get(3),btn2.get(0) });break;
					case 5:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn1.get(2), btn1.get(3),btn1.get(4) });break;
					default:break;
					}
					mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn1.get(2), btn1.get(3), btn1.get(4) });break;
				default:break;
				}
				btn_0.add(mainBtn);
			} else {
				// 一级菜单下面没有二级菜单
				if (bean.get("menuType").equals("click")) {
					CommonButton btnbe = new CommonButton();
					btnbe.setName(bean.get("menuName").toString());
					btnbe.setType(bean.get("menuType").toString());
					btnbe.setKey(bean.get("menuKey").toString());
					btn_2.add(btnbe);
				} else if (bean.get("menuType").equals("view")) {
					ViewButton btnbe = new ViewButton();
					btnbe.setName(bean.get("menuName").toString());
					btnbe.setType(bean.get("menuType").toString());
					btnbe.setUrl(bean.get("rebackContext").toString());
					btn_1.add(btnbe);
				}
			}
		}
		switch (btn_0.size() + btn_1.size() + btn_2.size()) {
		case 1:
			switch (btn_0.size()) {
			case 0:
				switch (btn_1.size()) {
				case 0: menu.setButton(new Button[] { btn_2.get(0) }); break;
				case 1: menu.setButton(new Button[] { btn_1.get(0) }); break;
				default: break;
				}break;
			case 1: menu.setButton(new Button[] { btn_0.get(0) }); break;
			default: break;
			}break;
		case 2:
			switch (btn_0.size()) {
			case 0:
				switch (btn_1.size()) {
				case 0:menu.setButton(new Button[] { btn_2.get(0), btn_2.get(1) });break;
				case 1:menu.setButton(new Button[] { btn_1.get(0), btn_2.get(0) });break;
				case 2:menu.setButton(new Button[] { btn_1.get(0), btn_1.get(1) });break;
				default:break;
				}break;
			case 1:
				switch (btn_1.size()) {
				case 0:menu.setButton(new Button[] { btn_0.get(0), btn_2.get(0) });break;
				case 1:menu.setButton(new Button[] { btn_0.get(0), btn_1.get(0) });break;
				default:break;
				}break;
			case 2:menu.setButton(new Button[] { btn_0.get(0), btn_0.get(1) });break;
			default:break;
			} break;
		case 3:
			switch (btn_0.size()) {
			case 0:
				switch (btn_1.size()) {
				case 0: menu.setButton(new Button[] { btn_2.get(0), btn_2.get(1), btn_2.get(2) }); break;
				case 1: menu.setButton(new Button[] { btn_1.get(0), btn_2.get(0), btn_2.get(1) }); break;
				case 2: menu.setButton(new Button[] { btn_1.get(0), btn_1.get(1), btn_2.get(0) }); break;
				case 3: menu.setButton(new Button[] { btn_1.get(0), btn_1.get(1), btn_1.get(2) }); break;
				default: break;
				} break;
			case 1:
				switch (btn_1.size()) {
				case 0: menu.setButton(new Button[] { btn_0.get(0), btn_2.get(0), btn_2.get(1) }); break;
				case 1: menu.setButton(new Button[] { btn_0.get(0), btn_1.get(0), btn_2.get(0) }); break;
				case 2: menu.setButton(new Button[] { btn_0.get(0), btn_1.get(0), btn_1.get(1) }); break;
				default: break;
				} break;
			case 2:
				switch (btn_1.size()) {
				case 0: menu.setButton(new Button[] { btn_0.get(0), btn_2.get(0) }); break;
				case 1: menu.setButton(new Button[] { btn_0.get(0), btn_1.get(0) }); break;
				default: break;
				} break;
			case 3: menu.setButton(new Button[] { btn_0.get(0), btn_0.get(1), btn_0.get(2) }); break;
			default: break;
			} break;
		default: break;
		}
		return menu;
	}

	/**
	 * 根据ID删除一条菜单记录（联动删除 一级和二级菜单全删）
	 */
	@Override
	public void deleteMenuById(InputObject inputObject, OutputObject outputObject) throws Exception {
		Map<String, Object> map = inputObject.getParams();
		Map<String, Object> bean = wechatMenuDao.selectMenuById(map);
		if(bean.get("wetherUser").toString().equals("0")){//未使用，可以删除
			wechatMenuDao.deleteMenuById(map);
		}else{
			outputObject.setreturnMessage("当前版本菜单正在使用中，不能删除！");
		}
		
	}

	/**
	 * 增加自定义菜单时，删除当前菜单项
	 */
	@Override
	public void deleteMenus(InputObject inputObject, OutputObject outputObject) throws Exception {
		Map<String, Object> map = inputObject.getParams();
		Map<String, Object> params = wechatMenuDao.selectMenuById(map);
		
		if(params.get("menuGrade").toString().equals("2")){//如果是二级菜单
			//直接根据ID删除该项
			wechatMenuDao.deleteMenuById(map);
			//获取该二级菜单所属的一级菜单
			params.put("id", params.get("menuBelong"));
			List<Map<String, Object>> beans = wechatMenuDao.selectMenuByBelong(params);
			//判断该二级菜单所属的一级菜单是否还有子节点
			if(beans.isEmpty()){//若为空的此一级菜单是否有子菜单的属性设置为0
				Map<String, Object> updateButton = new HashMap<>();
				updateButton.put("id", params.get("menuBelong"));
				updateButton.put("hasChild", 0);
				wechatMenuDao.updateMenuHasChildById(updateButton);
			}
		}else{//一级菜单删除该项，及父菜单为该一级菜单的子菜单
			wechatMenuDao.deleteMenuById(map);
			params.put("menuBelong", params.get("id"));
			wechatMenuDao.deleteMenuById(params);
		}
	}
}
